#include "pfunc_code.h"

#include <stdlib.h>
#ifdef WIN32
#include <stdio.h>
#endif

int pyfree::code(const unsigned char *buff, const int len, unsigned char *outbuf)
{
	char ch = 0;
	int nLen = 0;
	unsigned char * buf = (unsigned char *)buff;
	for (int i = 0; i < len; i++, nLen++)
	{
		ch = buf[i];
		if ((buf[i] | 0x0f) == 0xff && i > 0 && i < (len - 1))
		{
			*outbuf++ = 0xf0 & buf[i];
			*outbuf++ = 0x0f & buf[i];
			nLen += 1;
		}
		else {
			*outbuf++ = ch;
		}
	}
	buf = NULL;
	return nLen;
}

int pyfree::uncode(const unsigned char *buff, int len, unsigned char *outbuf)
{
	char ch = 0;
	int nLen = 0;
	unsigned char * buf = (unsigned char *)buff;
	for (int i = 0; i < len; i++, nLen++)
	{
		ch = buf[i];
		if (buf[i] == 0xf0)
		{
#ifdef _DEBUG
			if (i > len - 2)
				printf("Error!\r\n");
			if (buf[i + 1] > 0x0f)
				printf("Error!\r\n");
#endif
			ch = 0xf0 | buf[++i];
		}
		*outbuf++ = ch;
	}
	buf = NULL;
	return nLen;
}



//CRC校验
unsigned int  pyfree::crc16(unsigned char *ptr, unsigned int len)
{
	unsigned int wcrc = 0XFFFF;//预置16位crc寄存器，初值全部为1
	unsigned char temp;//定义中间变量
	unsigned int i = 0, j = 0;//定义计数

	for (i = 0; i < len; i++)//循环计算每个数据
	{
		temp = *ptr & 0X00FF;//将八位数据与crc寄存器亦或
		ptr++;//指针地址增加，指向下个数据
		wcrc ^= temp;//将数据存入crc寄存器
		for (j = 0; j < 8; j++)//循环计算数据的
		{
			if (wcrc & 0X0001)//判断右移出的是不是1，如果是1则与多项式进行异或。
			{
				wcrc >>= 1;//先将数据右移一位
				wcrc ^= 0XA001;//与上面的多项式进行异或
			}
			else//如果不是1，则直接移出
			{
				wcrc >>= 1;//直接移出
			}
		}
	}
	temp = wcrc;//crc的值
	return wcrc;
};
